package com.jarveis.frame.task;

import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.log4j.Logger;

/**
 * 任务对列
 * 
 * @author liuguojun
 */
public final class TaskQueue extends Thread {
	
	private static final Logger logger = Logger.getLogger(TaskQueue.class);

	private LinkedList<ITask> queue;
	private TaskPool taskPool;
	private TaskMonitor taskMonitor;
	private AtomicInteger size = new AtomicInteger(0);

	public TaskQueue(TaskPool taskPool) {
		this.queue = new LinkedList<ITask>();
		this.taskPool = taskPool;
		taskMonitor = taskPool.getTaskMonitor();
	}

	/**
	 * 添加任务到队列中
	 * 
	 * @param obj
	 */
	public synchronized void addTask(ITask task) {
		queue.addLast(task);
		size.incrementAndGet();
		notify();
	}

	/**
	 * 从队列中弹出任务或任务组对象
	 * 
	 * @return Object
	 */
	private ITask popTask() {
		ITask task = null;
		if (queue.isEmpty()) {
			size.set(0);
		} else {
			task = queue.removeFirst();
			size.decrementAndGet();
		}
		return task;
	}

	public synchronized void run() {
		try {
			while (true) {
				if (size.get() == 0) {
					wait();
				} else {
					if (taskPool.hasIdleTaskThread()) {
						// 线程池中有空闲线程，获取空闲线程来执行任务
						TaskThread taskThread = taskPool.getIdleTaskThread();
						taskThread.setTask(popTask());
						taskThread.startTask();
						//监视任务线程
						taskMonitor.push(taskThread);
					} else {
						sleep(9);
					}
				}
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
	}
}